package de.koller.worlders.engine.entity.mo.phsics;

import de.koller.oceanFramework.math.ROVec;
import de.koller.oceanFramework.math.Vec;

public class VelocityIterator {

	public static final double CLAMP_WAY = 1;
	private boolean clampWarned = false;
	
	private final PhysicsMO mo;
	private final Vec wishWay = new Vec();
	
	public VelocityIterator( PhysicsMO mo ) {
		this.mo = mo;
	}
	
	public void step( long elapsedTime ) {
		ROVec wf = mo.getForce();
		mo.getSelfForce().clear();
		mo.getEnergy().add( ( wf.getX() ) * elapsedTime, 
							( wf.getY() ) * elapsedTime );
		wishWay.set(	(mo.getVelocity().getX() + mo.getEnergy().getX()) * elapsedTime, 
						(mo.getVelocity().getY() + mo.getEnergy().getY()) * elapsedTime );
		clampWay( wishWay );
		mo.getMomov().getWay().set( wishWay );
	}

	private void clampWay( Vec deltaWay ) {
		boolean clamped = false;
		
		if( Math.abs( deltaWay.getX() ) > CLAMP_WAY ) {
			deltaWay.setX( deltaWay.getX() > 0 ? CLAMP_WAY : -CLAMP_WAY );
			clamped = true;
		}
		
		if( Math.abs( deltaWay.getY() ) > CLAMP_WAY ) {
			deltaWay.setY( deltaWay.getY() > 0 ? CLAMP_WAY : -CLAMP_WAY );
			clamped = true;
		}
		
		if( !clamped )
			clampWarned = false;
		if( clamped && !clampWarned ) {
			clampWarned = true;
			System.err.println( "Warning: Clamped way of " + mo.toString() );
		}
	}
	
}
